﻿
/*******************************************************************************************
// ©2009 Microsoft Corporation.  This code is provided under the Microsoft Public License.
*******************************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using Microsoft.Rtc.Collaboration;
using Microsoft.Rtc.Signaling;
using System.Diagnostics;

namespace ClientBilling
{
    /// <summary>
    /// Handles the sending of the INFO message that causes the extended window to appear in Communicator.
    /// </summary>
    public static class ExtendedWindowMessage
    {
        #region Constants
        private const string EXTENSIBILITY_MESSAGE = "<associatedData xmlns=\"http://schemas.microsoft.com/LCS/2007/04/CallAssociatedData\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://schemas.microsoft.com/LCS/2007/04/CallAssociatedData\"><associatedDataElement id=\"{0}\" purpose=\"CWurl\"><urlToHost>{1}</urlToHost><closeWithWindow>false</closeWithWindow></associatedDataElement></associatedData>";
        private const string EXTENSIBILITY_CONTENT_TYPE = "application/ms-call-associated-data+xml";
        #endregion

        private static int _extensibilityWindowId = 1;
        public static string FullApplicationPath { get; set; }

        /// <summary>
        /// Sends the INFO message with the URL for the extended window.
        /// </summary>
        /// <param name="infoMessageCall">The call in which to send the INFO message.</param>
        public static void SendToCall(Call infoMessageCall)
        {
            string link = string.Format("{0}ExtendedWindow/ExtendedWindow.aspx?{1}={2}", FullApplicationPath,
                ExtendedWindow.CONVERSATION_ID_QUERY_STRING, infoMessageCall.Conversation.Id);

            // We need to supply the INFO message as a byte array. The message itself is an XML document, whose format
            // you can see in the EXTENSIBILITY_MESSAGE constant.

            byte[] bytes = Encoding.UTF8.GetBytes(string.Format(EXTENSIBILITY_MESSAGE, _extensibilityWindowId++, link));

            // To send the INFO message, we use the BeginSendInfo method on the Call (not the Flow).
            // In order for the extended window to appear, the first parameter (the content type) 
            // should be "application/ms-call-associated-data+xml".

            infoMessageCall.EndSendInfo(
                infoMessageCall.BeginSendInfo(new System.Net.Mime.ContentType(EXTENSIBILITY_CONTENT_TYPE), bytes, null, null, null)
            );
        }
    }
}
